package com.xunshibao.bll.message.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.mapping.Array;

import com.xunshibao.bll.message.MessageLogic;
import com.xunshibao.core.dao.TransactionItem;
import com.xunshibao.core.dao.page.Pagination;
import com.xunshibao.dao.message.MessageDao;
import com.xunshibao.entity.message.Message;
import com.xunshibao.entity.message.MsgRelation;
import com.xunshibao.entity.message.MsgReply;
import com.xunshibao.service.message.MessageCatType;
import com.xunshibao.service.message.MessageSourceType;
import com.xunshibao.service.message.MessageStatus;

public class MessageLogicImpl implements MessageLogic {
	private MessageDao msgDao;

	public void setMsgDao(MessageDao msgDao) {
		this.msgDao = msgDao;
	}

	@Override
	public Message saveMessages(Long senderId, Integer sendDate, String senderName, String title, String content) {
		return new Message(senderId, senderName, title, content, sendDate, sendDate);
	}

	@Override
	public List<TransactionItem> saveRelations(Long senderId, Long receiverId, Long msgId, Integer sendDate, MessageCatType type) {
		List<TransactionItem> items = new ArrayList<TransactionItem>(2);
		// 消息接收人记录,设置isown为true,
		items.add(new TransactionItem(new MsgRelation(receiverId, msgId, type.getValue(), 100, "1", false, sendDate, null, sendDate)));
		switch (type) {
		case USER:// 站内信
			// 发送消息人的记录，设置isown为true,
			items.add(new TransactionItem(new MsgRelation(senderId, msgId, type.getValue(), 100, "0", true, sendDate, null, sendDate)));
			break;
		case SYSTEM:// 系统消息
			break;
		}
		return items;
	}

	@Override
	public TransactionItem saveReplies(Long msgId, Long createUid, Integer replyDate, String createUsername, String title, String content) {
		return new TransactionItem(new MsgReply(msgId, createUid, createUsername, title, content, MsgReply.UNREAD, replyDate, replyDate));
	}

	@Override
	public List<TransactionItem> updateMsgNums(Long uid, MessageCatType type) {
		List<TransactionItem> items = new ArrayList<TransactionItem>(2);
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = null;
		params.put("uid", uid);
		switch (type) {
		case SYSTEM:
			// 更新系统消息的条数
			hql = "update MsgConfig c set c.noticeNum = c.noticeNum + 1 where c.uid in(:uid)";
			items.add(new TransactionItem(hql, params));
			// 更新系统消息的条数
			hql = "update User u set u.syspm = u.syspm+1 where u.id=:uid";
			items.add(new TransactionItem(hql, params));
			break;
		case USER:
			// 更新用户消息的条数
			hql = "update MsgConfig c set c.smsNum = c.smsNum + 1 where c.uid in(:uid)";
			items.add(new TransactionItem(hql, params));
			// 更新用户消息的条数
			hql = "update User u set u.newpm = u.newpm+1 where u.id=:uid";
			items.add(new TransactionItem(hql, params));
			break;
		}
		return items;
	}

	@Override
	public int msgCount(Long userId, MessageCatType cat, MessageSourceType source, boolean isNew) {
		String hql = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("uid", userId);
		params.put("catid", cat.getValue());
		switch (source) {
		// 收件箱
		case RECEIVER:
//			params.put("isown", false);
			if (isNew) {
				// 收件箱新消息数
				params.put("status", "1");
				switch (cat) {
				case USER:
//					hql = "select count(r.relationId) as total from MsgRelation r where r.userid=:uid and r.catid=:catid and r.status=:status and r.isown=:isown";
					hql = "select count(r.relationId) as total from MsgRelation r where r.userid=:uid and r.catid=:catid and r.status=:status";
					break;
				case SYSTEM:
					hql = "select count(r.relationId) as total from MsgRelation r where r.userid=:uid and r.catid=:catid and r.status=:status and r.isown=:isown";
					hql = "select count(r.relationId) as total from MsgRelation r where r.userid=:uid and r.catid=:catid and r.status=:status";
					break;
				}
			} else {
				// 收件箱全部消息数
//				hql = "select count(r.relationId) as total from MsgRelation r where r.userid=:uid and r.catid=:catid and r.isown=:isown";
				hql = "select count(r.relationId) as total from MsgRelation r where r.userid=:uid and r.catid=:catid";
			}
			break;
		// 发件箱
		case SENDER:
//			params.put("isown", true);
			if (isNew) {
				// 发件箱新消息数
				params.put("status", "1");
//				hql = "select count(r.relationId) as total from MsgRelation r where r.userid=:uid and r.catid=:catid and r.status=:status and r.isown=:isown";
				hql = "select count(r.relationId) as total from MsgRelation r where r.userid=:uid and r.catid=:catid and r.status=:status";
			} else {
				// 收件箱全部消息数
//				hql = "select count(r.relationId) as total from MsgRelation r where r.userid=:uid and r.catid=:catid and r.isown=:isown";
				hql = "select count(r.relationId) as total from MsgRelation r where r.userid=:uid and r.catid=:catid";
			}
			break;
		default:
			break;
		}
		return ((Long) msgDao.findSingle(hql, params)).intValue();
	}

	@Override
	public Pagination getMsgRelation(Long userId, MessageCatType cat, MessageSourceType source, int pageNo, int pageSize) {
//		String hql = "select new MsgRelation(r.relationId, r.msgid, r.status) from MsgRelation r where r.userid=:uid and r.catid=:catid and r.isown=:isown order by r.modifydate desc";
		String hql = "select new MsgRelation(r.relationId, r.msgid, r.status) from MsgRelation r where r.userid=:uid and r.catid=:catid order by r.modifydate desc";

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("uid", userId);
		params.put("catid", cat.getValue());
//		switch (source) {
//		case SENDER:
//			params.put("isown", true);
//			break;
//		case RECEIVER:
//			params.put("isown", false);
//			break;
//		}
		return msgDao.pageFind(hql, pageNo, pageSize, params);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Message> getMsgList(List<Long> msgIds) {
		if (msgIds != null && msgIds.size() > 0) {
			// TODO 需要优化，只选择要显示的列
			String hql = "select m from Message m where m.msgId in (:msgIds)";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("msgIds", msgIds);
			return (List<Message>) msgDao.find(hql, params);
		} else {
			return null;
		}
	}

	@Override
	public TransactionItem resetNewMsgCount(List<Long> userIds) {
		// TODO 这里是清0还是-1，目前还不太清楚
		if (userIds != null && userIds.size() > 0) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userIds", userIds);
			String hql = "update MsgConfig c set c.smsNum=0 where c.uid in (:userIds)";
			return new TransactionItem(hql, params);
		} else {
			return null;
		}
	}

	@Override
	public TransactionItem[] userMsgCounts(List<Long> userIds) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public TransactionItem updateReplyStatus(List<Long> replyIds, MessageStatus status) {
		if (replyIds != null && replyIds.size() > 0) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("status", status.getValue());
			params.put("replyIds", replyIds);
			String hql = "update MsgReply r set r.status = :status where r.id in (:replyIds)";
			return new TransactionItem(hql, params);
		} else {
			return null;
		}
	}

	@Override
	public TransactionItem updateReplyViewDate(Long uid, List<Long> replyIds, Integer replyDate) {
		if (uid != null && replyIds != null && replyIds.size() > 0) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("modifytime", replyDate);
			params.put("status", "0");
			params.put("replyIds", replyIds);
			params.put("userid", uid);
			String hql = "update MsgRelation r set r.activedate=:modifytime, r.modifydate=:modifytime, r.status=:status where r.relationId in (:replyIds) and r.userid=:userid";
			return new TransactionItem(hql, params);
		} else {
			return null;
		}
	}

	@Override
	public List<TransactionItem> replyMsg(Long mid, Long uid, String username, Integer replyDate, String content) {
		List<TransactionItem> transItems = new ArrayList<TransactionItem>(3);
		String hql = null;
		// 回复对象
		MsgReply reply = new MsgReply(mid, uid, username, username, content, MsgReply.UNREAD, replyDate, replyDate);
		transItems.add(new TransactionItem(reply));
		
		// 更新消息内容
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("modifiedTime", replyDate);
		params.put("content", content);
		params.put("mid", mid);
		hql = "update Message msg set msg.modifiedTime=:modifiedTime, msg.content=:content where msg.msgId=:mid";
		transItems.add(new TransactionItem(hql, params));
		
		// 更新消息关联的状态
		params = new HashMap<String, Object>();
		params.put("status", "2");
		params.put("modifydate", replyDate);
		params.put("mid", mid);
		hql = "update MsgRelation r set r.status=:status, r.modifydate=:modifydate where mid=:mid";
		transItems.add(new TransactionItem(hql, params));
		return transItems;
	}

	@Override
	public List<TransactionItem> delete(Long rid, Long uid, Long mid) {
		List<TransactionItem> transItems = new ArrayList<TransactionItem>(2);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("rid", rid);
		params.put("uid", uid);
		String hql = "delete from MsgRelation r where r.relationId=:rid and r.userid=:uid";
		transItems.add(new TransactionItem(hql, params));
		
		params = new HashMap<String, Object>();
		params.put("mid", mid);
		hql = "delete from MsgReply r where r.createUid=:uid and r.msgId=:mid";
		transItems.add(new TransactionItem(hql, params));
		
		return transItems;
	}

}

